import { Repository , getRepository , FindManyOptions , In } from 'typeorm';
import { validate, ValidationError } from "class-validator";
import { Players } from '../entity/players';
import { BaseContext } from 'koa';

export default class PlayerControl {
    public static async savePlayer(players: Array<Players>) {
        const playerRepository: Repository<Players> = getRepository(Players);
        const errors: ValidationError[] = await validate(players);
        if(errors.length > 0) console.log(errors);
        else await playerRepository.save(players);
    }

    public static queryPlayersAll(): Promise<Array<Players>> {
        return new Promise(async (resolve,reject) => {
            const playerRepository: Repository<Players> = getRepository(Players);
            let players: Array<Players> = await playerRepository.find();
            resolve(players);
        })
    }

    public static async getPlayerLists(ctx: BaseContext) {
        try {
            const PlayerRepository: Repository<Players> = getRepository(Players);
            let { pageSize , pageIndex , id , teamsId } = ctx.request.body;
            pageIndex = pageIndex && pageIndex > 0 ? pageIndex-1 : 0;
            pageSize = pageSize || 10;
            let queryOptions: FindManyOptions<Players> = {
                relations: ["league","teams"],
                order: {
                    id: "DESC"
                },
                where: {},
                skip: pageIndex*pageSize,
                take: pageSize,
                cache: true,
            }
            let where = {};
            if(id && id !== '') Object.assign(where,{ id })
            if(teamsId && teamsId !== '') {
                let teamsArr = teamsId.split(',');
                Object.assign(where,{ "teams": In(teamsArr) })
            }
            queryOptions.where = where;
            const [ playerLists , total ] = await PlayerRepository.findAndCount(queryOptions);
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                playerLists,
                total
            });
        } catch (error) {
            ctx.status = 500;
            ctx.app.emit('error', {
                code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                message: ctx.ERROR.ERRORMSG_SYSTEMERROR
            }, ctx);
        }
    }

    public static async getPlayerIdList(ctx: BaseContext) {
        try {
            const PlayerRepository: Repository<Players> = getRepository(Players);
            const [ playerLists , total ] = await PlayerRepository.findAndCount({ select: ["id","displayName"] });
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                playerLists,
                total
            });
        } catch (error) {
            ctx.status = 500;
            ctx.app.emit('error', {
                code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                message: ctx.ERROR.ERRORMSG_SYSTEMERROR
            }, ctx);
        }
    }
}